/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable react-hooks/rules-of-hooks */
import React, { useRef, useState, memo, useEffect } from "react";
import { ProTable } from "@ant-design/pro-components";
import { doFetch, getFetch } from "@/utils/doFetch";
import { Tooltip } from "antd";

let handlEmptyChild = (tree = []) => {
  const newtree = tree.map((item) => {
    if (!item.children || item.children.length == 0) {
      item.value = item.key;
      return item;
    } else {
      item.value = item.key;
      return {
        ...item,
        children: handlEmptyChild(item.children),
      };
    }
  });
  return newtree;
};

const Mtable = (props) => {
  const {
    actionRef, //表格动作
    formRef, //表单Ref
    rowKey, // key
    columns = [], //columns
    style, //style
    path, //接口地址
    extraparams, //额外参数
    pageSize, //修改默认pageSize
    pagination, //分页设置
    x, //横向滚动
    activeTabKey, //激活的tabKey 拖拽表格唯一标识使用 其他情况用不到
    refreshDep, //依赖刷新 （已废弃）
    iscurrent = true,
  } = props;

  const actionRefs = actionRef ?? useRef(),
    formRefs = formRef ?? useRef(),
    ifspagination = pagination == "false" || pagination === false,
    [size, setsize] = useState("small"),
    [valueColumns, setvalueColumns] = useState({});
  const [columnes, setcolumnes] = useState(
    columns
      ?.filter?.((it) => it.valueType != "split")
      ?.map((it) => {
        const newit = { ...it };
        delete newit?.formItemProps;
        const render = it?.render
          ? {}
          : {
              render: (text, row) => {
                return (
                  <Tooltip title={row[it.dataIndex]} placement="topLeft">
                    <span className="table-cell">{text ?? "-"}</span>
                  </Tooltip>
                );
              },
            };

        const search = it?.hideInTable
          ? {
              search: false,
            }
          : {};

        let options = {};
        if (
          ["select", "treeSelect", "radio", "checkbox", "cascader"].includes(
            it?.valueType
          )
        ) {
          if (Array.isArray(it.options)) {
            options = {
              fieldProps: {
                ...it?.fieldProps,
                options: [...it.options],
                popupMatchSelectWidth: 200,
              },
            };
          } else if (it.options) {
            options = {
              fieldProps: {
                ...it?.fieldProps,
                popupMatchSelectWidth: 200,
                showSearch: true,
              },
              //params: paramconfig[curkey],
              request: async (parames) => {
                delete parames?.keyWords;
                if (Object.keys(it?.options).includes("linkParams")) {
                  let list = await getFetch({
                    url: it?.options?.path,
                    params: { ...parames, is_all: 1 },
                  });
                  const res = list?.data?.dataList
                    ? list?.data?.dataList?.map((its) => {
                        return {
                          label: its[it?.options?.tlabel] ?? its?.name,
                          value: its[it?.options?.tvalue] ?? its?.id,
                        };
                      })
                    : [];
                  return it.valueType == "treeSelect"
                    ? handlEmptyChild(res)
                    : res;
                } else {
                  let list = await getFetch({
                    url: it?.options?.path,
                    params: it?.options?.params,
                  });
                  const res = list?.data?.dataList
                    ? list?.data?.dataList?.map((its) => {
                        return {
                          label: its[it?.options?.tlabel] ?? its?.name,
                          value: its[it?.options?.tvalue] ?? its?.id,
                        };
                      })
                    : [];
                  return it.valueType == "treeSelect"
                    ? handlEmptyChild(res)
                    : res;
                }
              },
            };
          }
        }

        if (it.valueType == "option") {
          options = {
            key: "option",
            dataIndex: "option",
            fixed: "right",
          };
        }

        return {
          ...newit,
          valueType: it?.searchvalueType ?? it?.valueType,
          ...render,
          ...search,
          ...options,
        };
      }) ?? []
  );

  //调用接口
  const request = async (params, sort, filter) => {
    if (!path) return;
    if (params?.date) {
      params.date = params?.date?.toString();
    }
    if (params?.in_store_date) {
      params.in_store_date = params?.in_store_date?.toString();
    }
    if (params?.back_date) {
      params.back_date = params?.back_date?.toString();
    }

    let newparams = {
      ...params,
      ...extraparams, //父组件传参
      pageIndex: params.current,
      pageSize: params.pageSize || pageSize,
    };
    delete newparams.current;
    if (ifspagination) {
      delete newparams.pageIndex;
      delete newparams.pageSize;
    }
    const result = await getFetch({ url: path, params: newparams });
    //分页结果
    let data = result?.data?.list,
      success = true,
      total = result?.data?.total;
    //不带分页获取结果
    if (ifspagination) {
      data = result?.data?.dataList;
      total = result?.data?.dataList?.length;
    }
    return {
      data,
      success,
      total,
    };
  };

  //调用重新渲染表格
  useEffect(() => {
    iscurrent && actionRefs?.current?.reload();
    return () => {};
  }, [columns, extraparams, path, activeTabKey, refreshDep, iscurrent]);

  return (
    <ProTable
      {...props}
      size={size}
      onSubmit={(params) => {
        console.log(params, "onSubmit");
      }}
      onSizeChange={(size) => {
        localStorage.setItem("size", size); //设置全局表格规格缓存
        setsize(size);
      }}
      columns={columnes ?? []}
      style={style || {}}
      actionRef={actionRefs}
      formRef={formRefs}
      rowKey={rowKey ?? "id"} //表格每行数据的key
      dateFormatter="string"
      request={request}
      pagination={
        ifspagination
          ? false
          : {
              showTotal: (total, range) => <span>共{total}条</span>,
              showQuickJumper: true,
              showSizeChanger: false,
              pageSizeOptions: [5, 10, 15, 30, 50, 100, 200],
              defaultPageSize: pageSize || 15,
            }
      }
      search={{
        filterType: "light", //轻量模式
        placement: "bottomLeft",
      }}
    />
  );
};

export default memo(Mtable);
